﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace Itfort.Install
{
	/// <summary>
	/// 
	/// </summary>
	[RunInstaller(true)]
	public class InstallerEx : Installer
	{
		private string m_ServiceName;
		private ServiceInstaller m_ServiceInstaller;
		private ServiceProcessInstaller m_ServiceProcessInstaller;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="serviceName"></param>
		public InstallerEx(string serviceName)
		{
			m_ServiceName = serviceName;
			this.Init();
		}

		void Init()
		{
			ServiceInstaller serviceInstaller = this.GetServiceInstaller();
			ServiceProcessInstaller serviceProcessInstaller = this.GetServiceProcessInstaller();

			this.Installers.AddRange(new Installer[] {
				serviceInstaller,
				serviceProcessInstaller
			});

			this.Context = this.GetInstallContext();
		}

		ServiceInstaller GetServiceInstaller()
		{
			if (m_ServiceInstaller == null)
			{
				m_ServiceInstaller = new ServiceInstaller();
				m_ServiceInstaller.ServiceName = m_ServiceName;
				m_ServiceInstaller.DisplayName = m_ServiceName + "的显示名称";
				m_ServiceInstaller.Description = m_ServiceName + "的详细描述";
			}
			return m_ServiceInstaller;
		}

		ServiceProcessInstaller GetServiceProcessInstaller()
		{
			if (m_ServiceProcessInstaller == null)
			{
				m_ServiceProcessInstaller = new ServiceProcessInstaller();
				m_ServiceProcessInstaller.Account = ServiceAccount.NetworkService;
			}
			return m_ServiceProcessInstaller;
		}

		InstallContext GetInstallContext()
		{
			string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "installer.log");

			string path = string.Format("/assemblypath={0}", System.Reflection.Assembly.GetExecutingAssembly().Location);
			string[] commandLine = { path };

			InstallContext installContext = new InstallContext(logFilePath, commandLine);
			return installContext;
		}
	}
}
